import 'package:dio/dio.dart';
import 'package:flutter_base_plugin/base_library/base/view_model/base_view_model.dart';
import 'package:flutter_base_plugin/base_library/base_network/x_api.dart';

import '../../base_network/bean/http_error_bean.dart';
import '../../base_utils/log_utils.dart';

abstract class BaseObjViewModel<T> extends BaseViewModel {
  ///进入页面时（首次）调用接口是否成功
  bool _isLoadingSuccess = false;

  ///数据源:针对单个对象请求，获取的数据
  T? data;

  ///请求失败回调,子类根据需求重写
  ///[errorBean] http失败响应对象
  ///[isLoadMoreFailCallback] 是否是加载更多失败时回调
  void onHttpErrorCallback(HttpErrorBean errorBean) {}

  ///************************下面是必须重写的方法***************************
  ///获取http请求参数
  Map<String, dynamic> getRequestParams();

  ///获取http请求url
  String getUrl();

  // ///配置当前请求Options
  // ///子类根据需要可以重写该方法
  // Options? configHttpOptions() {
  //   return null;
  // }

  ///请求失败是否显示Toast提示错误信息
  ///子类根据需求重写
  ///[isLoadMore] 是否是加载更多时，回调的该方法
  bool configIsShowFailToast(bool isLoadMore) {
    return true;
  }

  //加载数据
  ///第一次请求或下拉刷新时调用(请求参数设置为初始值)
  @override
  Future onLoading() async {
    if (isLoading) {
      LogUtils.d(getTag(), 'onLoading() is Loading');
      return;
    }
    isLoading = true;
    CancelToken cancelToken = CancelToken();
    cancelTokenList.add(cancelToken);

    ///请求失败回调
    var onError = (HttpErrorBean errorBean) {
      ///进入页面时（首次）调用接口是否成功
      _isLoadingSuccess = false;
      isLoading = false;
      error = errorBean;
      onHttpErrorCallback(errorBean);
    };

    ///请求完成回调
    var onComplete = () {
      isLoading = false;
      cancelTokenList.remove(cancelToken);
    };

    ///请求单个数据对象
    await api.request<T>(
      getUrl(),
      Method.GET,
      params: getRequestParams(),
      // option: configHttpOptions(),
      isShowLoading: false,
      isShowFailToast: configIsShowFailToast(false),
      cancelToken: cancelToken,
      onError: onError,
      onComplete: onComplete,
      onSuccess: (T? bean) {
        ///请求成功回调
        _isLoadingSuccess = true;
        data = bean;
        isLoading = false;
        notifyListeners();
      },
    );
  }

  ///请求是否成功
  @override
  bool isSuccess() {
    if (_isLoadingSuccess) {
      return data != null;
    } else {
      return false;
    }
  }

  ///请求是否失败
  @override
  bool isFail() {
    return !_isLoadingSuccess;
  }

  ///请求数据是否为空
  @override
  bool isEmpty() {
    return data == null;
  }
}
